package com.qiaofang.common.utils;

import com.alibaba.fastjson.JSON;
import com.qiaofang.common.config.SystemConfig;
import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 上传图片
 */
@Slf4j
public class UploadFileUtil {

    public static String uploadFile(String type, MultipartFile multipartFile) {
        String result = HttpUtil.httpClientUploadFile(SystemConfig.uploadFileUrl, type, multipartFile);
        UploadFileResult uploadFileResult = JSON.parseObject(result, UploadFileResult.class);
        return uploadFileResult.getUrl();
    }

    public static void uploadWxJs(MultipartFile multipartFile) {
        try {
            uploadWxJs(multipartFile, "/data/multiuser/apache-tomcat-7-4/webapps/");
            uploadWxJs(multipartFile, "/data/multiuser/apache-tomcat-7-6/webapps/");
        } catch (IOException e) {
            log.error("上传文件失败: {}", e);
            throw new BusinessException(ExceptionEnum.UPLOAD_WX_CONFIG);
        }
    }

    public static void uploadWxJs(MultipartFile multipartFile, String filePath) throws IOException {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
            File file = new File(filePath + "/" + multipartFile.getOriginalFilename());
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int size = -1;
            // 每次读取1KB，直至读完
            while ((size = inputStream.read(temp)) != -1) {
                outputStream.write(temp, 0, size);
            }

            log.info("微信文件上传成功.");
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }

}
